const mysql = require('mysql2/promise');

async function main() {
    const args = process.argv.slice(2);
    let playerId = 0, playerDeputyId = 0, deputyIdArg = 0, level = 1;
    for (let i = 0; i < args.length; i++) {
        if (args[i] === '--player' && args[i + 1]) playerId = parseInt(args[i + 1], 10);
        if (args[i] === '--pd' && args[i + 1]) playerDeputyId = parseInt(args[i + 1], 10);
        if (args[i] === '--dep' && args[i + 1]) deputyIdArg = parseInt(args[i + 1], 10);
        if (args[i] === '--level' && args[i + 1]) level = parseInt(args[i + 1], 10);
    }
    if (!playerId || !level || (!playerDeputyId && !deputyIdArg)) {
        console.error('用法: node scripts/set-deputy-level.js --player 2001 --pd 1 --level 50 或 --dep 123');
        process.exit(1);
    }

    const db = {
        host: process.env.DB_HOST || '43.143.253.188',
        port: parseInt(process.env.DB_PORT || '3306', 10),
        user: process.env.DB_USER || 'nextjs',
        password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
        database: process.env.DB_NAME || 'nextjs',
    };

    const getCap = (transCount) => {
        if (!transCount || transCount <= 0) return 100;
        if (transCount === 1) return 120;
        if (transCount === 2) return 140;
        return 160;
    };

    let conn;
    try {
        conn = await mysql.createConnection(db);
        let deputyId = deputyIdArg;
        if (!deputyId) {
            const [pdRows] = await conn.execute(
                'SELECT id, deputy_id, player_id FROM player_deputy WHERE id = ? AND player_id = ? LIMIT 1',
                [playerDeputyId, playerId]
            );
            if (!pdRows || !pdRows[0]) {
                console.error('未找到该玩家的 player_deputy 记录');
                process.exit(1);
            }
            deputyId = pdRows[0].deputy_id;
        }

        const [depRows] = await conn.execute(
            'SELECT trans_count FROM deputy_general WHERE id = ? LIMIT 1',
            [deputyId]
        );
        if (!depRows || !depRows[0]) {
            console.error('未找到副将记录');
            process.exit(1);
        }
        const transCount = parseInt(depRows[0].trans_count || 0, 10) || 0;
        const cap = getCap(transCount);
        if (level > cap) {
            console.error(`禁止设置超过上限的等级：当前转职=${transCount}，上限=${cap}，传入=${level}`);
            process.exit(1);
        }

        const [lvRows] = await conn.execute(
            'SELECT experience FROM level_experience WHERE level = ? LIMIT 1',
            [level]
        );
        let expRemain = 0;
        if (lvRows && lvRows[0] && lvRows[0].experience != null) {
            expRemain = Number(lvRows[0].experience) || 0;
        }

        await conn.execute(
            'UPDATE deputy_general SET lvl = ?, exp = ?, updated_at = NOW() WHERE id = ?',
            [level, expRemain, deputyId]
        );
        console.log(`已将 deputy_id=${deputyId} 设置为 lvl=${level}, exp=${expRemain}（转职=${transCount}, 上限=${cap}）`);
    } catch (e) {
        console.error('设置失败:', e && e.message ? e.message : e);
        process.exit(1);
    } finally {
        if (conn) await conn.end();
    }
}

main().catch(e => { console.error(e); process.exit(1); });
